package org.xukai.remoting.ws;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import javax.xml.ws.soap.SOAPBinding;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.net.URL;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class WsTest {
    /**
     * 接口地址
     */
//    private static String webURL = "http://127.0.0.1:10001/";
////    private static String webURL = "file:\\C:\\Users\\Administrator\\Desktop\\test.wsdl";
////    private static String wsdlPrefix = webURL + "himapws/webservice!viewWsdl.action?serviceName=";
//    private static String endpoint = webURL + "/webServices/himapEntryPort";
    private static String nsPrefix = "http://ws.server.himap.com/";
//    private static String serviceName = "himapEntryService";
//    private static String portName = "himapEntryPort";
    private static String webURL = "http://127.0.0.1:8076";
    private static String endpoint = webURL + "/webServices";
//    private static String nsPrefix = "http://www.guahao.com";
    private static String serviceName = "himapEntryService";
    private static String portName = "himapEntryPort";

    public static void main2(String[] args) throws DocumentException {
        exception();
    }

    public static void main(String[] args) throws Exception {
        final String method = "demo";// 具体要调用某个流程
        final String param = "<startDate>20151001</startDate>";
        ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        final AtomicInteger atomicInteger = new AtomicInteger(0);
//        ScheduledFuture<?> future = service.scheduleWithFixedDelay(new Runnable() {
//            @Override
//            public void run() {
//                String result = null;
//                try {
//                    result = invoke(endpoint, nsPrefix,
//                            serviceName, portName, method, param);
//                    atomicInteger.incrementAndGet();
//                    if (atomicInteger.get() > 5) {
//                        countDownLatch.countDown();
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                System.out.println("收到:" + result);
//            }
//        }, 5000, 2000, TimeUnit.MILLISECONDS);
        String result = null;

                    result = invoke(endpoint, nsPrefix,serviceName, portName, method, param);
        System.out.println(result);
//        System.out.println("开始等待");
//        countDownLatch.await();
//        System.out.println("关闭线程");
//        future.cancel(true);
    }


    /**
     * 调用服务
     *
     * @param endpoint
     * @param ns
     * @param serviceName
     * @param portName
     * @param method
     * @param param
     * @return
     * @throws Exception
     */
    private static String invoke(String endpoint, String ns,
                                 String serviceName, String portName, String method, String param)
            throws Exception {
        URL wsdlURL = new URL("http://localhost:8076/alonewsflow/getWsdlContent/demo");
        Source response = null;
        try {
            QName port = new QName(ns, portName);
            Service service = Service.create(wsdlURL,new QName(ns, serviceName));
            service.addPort(port, SOAPBinding.SOAP11HTTP_BINDING, endpoint);
            Dispatch<Source> disp = service.createDispatch(port, Source.class,
                    Service.Mode.PAYLOAD);
            String request = String
                    .format("<ns2:%1$s_Request xmlns:ns2=\"%2$s\"><request>%3$s</request></ns2:%1$s_Request>",
                            method, ns, param);
            response = disp.invoke(new StreamSource(
                    new StringReader(request)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sourceToXMLString(response);
    }

    /**
     * 将source转换为字符串
     *
     * @param result
     * @return
     */
    private static String sourceToXMLString(Source result) throws Exception {
        String xmlResult = null;
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        StreamResult streamResult = new StreamResult();
        streamResult.setOutputStream(out);

        transformer.transform(result, streamResult);
        xmlResult = out.toString("UTF-8");
        return xmlResult;
    }

    private static void exception() throws DocumentException {
        String s4 = "\t  \n" +
                "\t  <ns2:demo_Response xmlns:ns2=\"http://ws.server.himap" +
                ".com/demo\"><response><Body>null</Body></response><response><Body>null</Body" +
                "></response></ns2:demo_Response>";
        Document document = DocumentHelper.parseText(s4);
        Element rootElement = document.getRootElement();
//        List elements = rootElement.elements();
        List elements = rootElement.selectNodes("response");
        for (int i = 0; i < elements.size(); i++) {
            Element element = (Element) elements.get(i);
            String body = element.element("Body").getText();
            if (null != body && body.indexOf("null") != 0) {
                System.out.println(body);
            }

        }
    }
}
